package com.shop.service.shop.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.service.module.entity.Result;
import com.shop.service.module.entity.TeamEntity;
import com.shop.service.module.mapper.TeamMapper;
import com.shop.service.module.service.TeamService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/team")
public class TeamController {
    @Autowired

    private TeamService teamService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("list/page")
    @Cacheable(value = "teamList", condition = "true")
    public Result getListPage(@RequestParam(value = "pno", defaultValue = "1", required = false) int pno,
                              @RequestParam(value = "psize", defaultValue = "10", required = false) int psize,
                              @RequestParam(value = "name", defaultValue = "", required = false) String name,
                              @RequestParam(value = "isOnSale", required = false) Integer isOnSale,
                              @RequestParam(value = "type", required = false) Integer type) {
        return teamService.getListForPage(pno, psize, name, isOnSale, type);
    }

    @PutMapping("insert")
    @CacheEvict(value = "teamList", allEntries = true)
    public Result insert(@RequestBody TeamEntity teamEntity) {
        teamEntity.setInsertTime(new Date());
        teamEntity.setIsOnSale(0);
        //设置活动参与人为0
        teamEntity.setHasMember(0);
        //设置活动状态初始值
        teamEntity.setStatus(0);
        boolean result = teamService.save(teamEntity);
        //获取当前时间
        long timestamp = System.currentTimeMillis();
        //获取截止时间
        long endTimestamp = teamEntity.getEndTime().getTime();
        //得到剩余多久过期
        long expireTime = endTimestamp - timestamp;
        if (result) {
            JSONObject data = new JSONObject();
            data.put("id", teamEntity.getId());
            //通知消息队列在一定期限内设置活动过期
            rabbitTemplate.convertAndSend("teamTimeOutExchange",
                    "teamTimeOutRouter",
                    data,
                    message -> {
                        message.getMessageProperties().setExpiration(expireTime + "");
                        return message;
                    }

            );
        }
        return result ? Result.end(200, "", "添加成功") : Result.end(500, "", "添加失败");
    }

    @GetMapping("find/id/{id}")
    public Result findTeamById(@PathVariable("id") Long id) {
        TeamEntity teamEntity = teamService.getById(id);

        return Result.end(200, teamEntity, "查询成功");
    }

    @PutMapping("update")
    @CacheEvict(value = "teamList", allEntries = true)
    public Result update(@RequestBody TeamEntity teamEntity) {
        boolean result = teamService.updateById(teamEntity);
        return result ? Result.end(200, "", "修改成功") : Result.end(500, "", "修改失败");
    }

    @DeleteMapping("delete/id/{id}")
    @CacheEvict(value = "teamList", allEntries = true)
    public Result delete(@PathVariable("id") Long id) {
        boolean result = teamService.removeById(id);
        return result ? Result.end(200, "", "删除成功") : Result.end(500, "", "删除失败");
    }

    @GetMapping("set/onsale")
    @CacheEvict(value = "teamList", allEntries = true)
    public Result setOnsale(@RequestParam("id") Long id,
                            @RequestParam("isOnSale") Integer isOnSale) {
        TeamEntity teamEntity = teamService.getById(id);
        teamEntity.setIsOnSale(isOnSale);
        boolean result = teamService.updateById(teamEntity);
        return result ? Result.end(200, "", "修改成功") : Result.end(500, "", "修改失败");

    }

    @PostMapping("insert/team")
    @CacheEvict(value = "teamList", allEntries = true)
    public Result insertTeam(@RequestParam("id") Long id,
                            HttpServletRequest request) {
        //从header中提取鉴权字符串
        String authorization = request.getHeader("Authorization");
        System.out.println(authorization);
        //从加密字符串中去掉Bearer字样
        authorization = authorization.replace("Bearer ","");
        //通过jwt解密工具将密文解密成原始对象
        Jwt jwtInfo = JwtHelper.decode(authorization);
        //将jwt原始对象转换成字符串
        String jwtStr = jwtInfo.getClaims();
        System.err.println(jwtStr);
        //将jwt的字符串转换成json对象
        JSONObject jwtJSON = JSONObject.parseObject(jwtStr);
        //将userInfo这个属性的结果提取并转换成json对象，得到用户信息的json数据
        JSONObject userObject = JSONObject.parseObject(jwtJSON.get("userInfo").toString());
        //从用户信息中提取用户id
        String userId = userObject.get("id").toString();
        //输出用户id
        System.err.println("请求用户的id为"+id);
        return teamService.insertTeam(id,userId);
    }
    @GetMapping("get/result")
    public Result getResult(  @RequestParam("id") Long id,
                              HttpServletRequest request){
//从header中提取鉴权字符串
        String authorization = request.getHeader("Authorization");
        System.out.println(authorization);
        //从加密字符串中去掉Bearer字样
        authorization = authorization.replace("Bearer ","");
        //通过jwt解密工具将密文解密成原始对象
        Jwt jwtInfo = JwtHelper.decode(authorization);
        //将jwt原始对象转换成字符串
        String jwtStr = jwtInfo.getClaims();
        System.err.println(jwtStr);
        //将jwt的字符串转换成json对象
        JSONObject jwtJSON = JSONObject.parseObject(jwtStr);
        //将userInfo这个属性的结果提取并转换成json对象，得到用户信息的json数据
        JSONObject userObject = JSONObject.parseObject(jwtJSON.get("userInfo").toString());
        //从用户信息中提取用户id
        String userId = userObject.get("id").toString();
        //输出用户id
        System.err.println("请求用户的id为"+id);
        return teamService.getResult(id,userId);
    }
    @GetMapping("/list/alive")
    public Result getListAlive(){
        QueryWrapper q = new QueryWrapper();
        q.eq("status",0);
        q.apply("UNIX_TIMESTAMP(current_time) < UNIX_TIMESTAMP(end_time)");
        List list = teamService.list(q);
        JSONObject j = new JSONObject();

        j.put("list",list);

        return Result.end(200,j,"查询成功");
    }

}
